<?php


namespace App\Services;

use App\Models\UserMessageCount;

class MessageCountService extends BaseService
{
    private $_repository;

    public function __construct()
    {
        parent::__construct();
        $this->_repository = repository()->MessageCountRepository;
    }

    /**
     * 新增用户某类型未读消息记录
     * @param $loadData
     * @return UserMessageCount|false|\Illuminate\Database\Eloquent\Builder|object
     */
    public function createMessageCount($loadData)
    {
        $userMessageCount = $this->_repository->getUserMsgCountByUserIdAndMsgType($loadData['user_id'], $loadData['message_type']);
        if ($userMessageCount) {
            return $userMessageCount;
        }

        return $this->_repository->createMessageCount([
            'user_id' => $loadData['user_id'],
            'message_type' => $loadData['message_type'],
            'count' => 1,
        ]);
    }

    /**
     * 更新用户某类型未读消息数
     * @param $loadData
     * @return UserMessageCount|false|\Illuminate\Http\JsonResponse
     */
    public function updateMessageCount($loadData)
    {
        $userMessageCount = $this->_repository->getUserMsgCountByUserIdAndMsgType($loadData['user_id'], $loadData['message_type']);
        if (!$userMessageCount) {
            $this->createMessageCount($loadData);
        }

        return $this->_repository->updateMessageCount($userMessageCount, [
            'count' => $loadData['count']
        ]);
    }
}
